<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="userRegister"
    @ok="confirmSubmit"
    @close="drawerReset"
    width="1000"
    showFooter
    isAbsolute
    getContainer=".page-wrapper"
  >
    <div class="user-drawer" ref="eleRef">
      <BasicForm @register="userForm">
        <template #channelType="{ model, field }">
          <div class="drawer-check" v-if="drawerInfo.type !== operateActionTypeMap.VIEW">
            <a-checkbox-group v-model:value="model[field]" :options="drawerInfo.checkOptions" @change="checkChange" />
          </div>
          <div class="drawer-check" v-else>
            {{ channelTypeStr || '--' }}
          </div>
        </template>
        <template #channelFlag="{ model, field }">
          <div class="drawer-flex">
            <a-switch
              v-model:checked="model[field]"
              :disabled="drawerInfo.type !== operateActionTypeMap.ADD"
              checked-children="启用"
              un-checked-children="关闭"
              checkedValue="1"
              unCheckedValue="0"
            />
            <div class="switch-info">
              <info-circle-outlined
                :style="{
                  fontSize: '16px',
                  color: '#C0C0C0'
                }"
              />
              <div class="info-txt">注意：如果当前用户是渠道用户，则需要开启此开关</div>
            </div>
          </div>
        </template>
        <template #parentChannelCode="{ model, field }">
          <a-tree-select
            v-model:value="model[field]"
            :tree-data="channelTreeData"
            @change="treeSelectChange(model[field])"
            :field-names="{
              label: 'channelName',
              value: 'channelCode',
              children: 'children'
            }"
            placeholder="请选择上级渠道"
            treeNodeFilterProp="channelName"
            showSearch
            allowClear
          ></a-tree-select>
        </template>
        <template #roleIdList="{ model, field }">
          <template v-if="drawerInfo.type !== operateActionTypeMap.VIEW">
            <a-select
              :options="drawerInfo.roleList"
              :defaultActiveFirstOption="false"
              mode="multiple"
              :maxTagCount="5"
              placeholder="请选择用户角色"
              :filter-option="filterOption"
              show-search
              v-model:value="model[field]"
              allowClear
            />
          </template>
          <template v-else> {{ roleStr || '--' }} </template>
        </template>
      </BasicForm>
      <!-- <div class="box-auth" v-loading="roleLoading">
        <div class="auth-title global-asterisk-require">用户角色</div>
        <div class="auth-list" v-if="drawerInfo.type === operateActionTypeMap.VIEW">
          <div class="list-item" v-for="item in drawerInfo.viewRole" :key="item.roleId">{{ item.roleName }}</div>
          <Empty v-if="!drawerInfo.viewRole.length && emptyInit"></Empty>
        </div>
        <div class="auth-list" v-else>
          <a-checkbox-group v-model:value="drawerInfo.roleIdList" :options="drawerInfo.roleList" />
          <Empty v-if="!drawerInfo.roleList.length && emptyInit"></Empty>
        </div>
      </div> -->
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { BasicDrawer, useDrawerInner } from '@/components/Drawer'
import { BasicForm, FormSchema, useForm } from '@/components/Form/index'
import Empty from '@/components/Empty/index.vue'
import { operateActionType } from '@/types/enum'
import { getUpdateSchemaArr } from '@/utils/formSchema'
import { numTransString, scrollToFirstError, transformToTree, createChannelTree } from '@/utils'
import { getUserFormConfig } from '../dataSource'
import { message } from 'ant-design-vue'
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import { cloneDeep } from 'lodash-es'
import { UserAddRecord, RoleRecord } from '@/types/system'
import api from '@/api'

const { userAdd, userUpdate, userDetail, roleList, resetPwd, userQueryChannelList } = api

const emit = defineEmits(['operateSuccess', 'resetPwd', 'register'])
const eleRef = ref<null | HTMLElement>(null)

const operateActionTypeMap = operateActionType
const roleLoading = ref(false)
const emptyInit = ref(false)
const drawerInfo = reactive<any>({
  type: '',
  userId: '',
  record: {},
  viewRole: [],
  roleList: [],
  roleIdList: [],
  checkOptions: [
    {
      label: 'BPai产品渠道',
      value: '2',
      disabled: false
    },
    {
      label: '数票通产品渠道',
      value: '1',
      disabled: false
    }
  ]
})
const channelTreeData = ref<any>([])
const seclectedChannel = ref('')

const channelTypeStr = ref('')
const roleStr = ref('')

const treeSelectChange = (data: any) => {
  seclectedChannel.value = data
}

const userFormConfig = getUserFormConfig()
const [userForm, { setFieldsValue, getFieldsValue, validate, resetFields, updateSchema }] = useForm(userFormConfig)

const [userRegister, { closeDrawer, changeOkLoading }] = useDrawerInner(async (data) => {
  drawerInfo.type = data.type
  emptyInit.value = false
  getChannelList('3')
  // 查看时表单展示
  updateSchema(getUpdateSchemaArr(userFormConfig.schemas, data.type))

  if (data.type !== operateActionTypeMap.VIEW) {
    try {
      roleLoading.value = true
      let roleRes = await roleList({
        page: {
          pageNo: 1,
          pageSize: 999
        }
      })
      let roleListArr = roleRes.result?.records
      if (roleListArr.length) {
        roleListArr = roleListArr.map((item: RoleRecord) => {
          return {
            label: item.roleName,
            value: item.roleId
          }
        })
      }
      roleLoading.value = false
      drawerInfo.roleList = roleListArr
    } catch (error) {
      roleLoading.value = false
    }
  }
  if (data.type === operateActionTypeMap.VIEW) {
    updateSchema([
      {
        field: 'parentChannelCode',
        component: 'BasicTxt'
      },
      {
        field: 'channelFlag',
        component: 'BasicTxt'
      }
    ])
  }
  updateSchema([
    {
      field: 'userAccount',
      componentProps: {
        disabled: data.type === operateActionTypeMap.EDIT
      }
    },
    {
      field: 'feeModel',
      componentProps: {
        disabled: data.type === operateActionTypeMap.EDIT
      }
    },
    {
      field: 'channelCode',
      componentProps: {
        disabled: data.type !== operateActionTypeMap.ADD
      }
    }
  ])

  if (data.type !== operateActionTypeMap.ADD) {
    let record = cloneDeep(data.record)
    drawerInfo.userId = record.userId
    drawerInfo.record = record
    try {
      roleLoading.value = true
      let detailRes = await userDetail({ userId: record.userId })
      if (detailRes.result) {
        roleLoading.value = false
        let rolePermit = detailRes.result?.rolePermit
        let roleIdList: string[] = []
        if (rolePermit && rolePermit.length) {
          rolePermit.forEach((item: RoleRecord) => {
            roleIdList.push(item.roleId)
          })
        }
        if (data.type === operateActionTypeMap.EDIT) {
          drawerInfo.roleIdList = roleIdList
        } else {
          let rolePermitArr = rolePermit.map((item: any) => item.roleName)
          roleStr.value = rolePermitArr && rolePermitArr.length > 0 ? rolePermitArr.join('、') : ''
        }

        let channelType = detailRes.result.channelType
        if (channelType) {
          channelType = channelType == '3' ? ['1', '2'] : [channelType]
          const channelTypeMap: any = {
            '1': '数票通产品渠道',
            '2': 'BPai产品渠道',
            '3': 'BPai产品渠道、数票通产品渠道'
          }
          channelTypeStr.value = channelTypeMap[detailRes.result.channelType]
        } else {
          channelType = []
          channelTypeStr.value = ''
        }

        setFieldsValue({
          ...detailRes.result,
          parentChannelCode:
            data.type === operateActionTypeMap.VIEW
              ? detailRes.result.parentChannelCodeName
              : detailRes.result.parentChannelCode,
          userStatus: numTransString(record.userStatus),
          channelType,
          roleIdList: drawerInfo.roleIdList,
          channelFlag: numTransString(record.channelFlag)
        })
        if (data.type === operateActionTypeMap.EDIT) {
          drawerInfo.checkOptions[0].disabled = ['2', '3'].includes(detailRes.result.channelType)
          drawerInfo.checkOptions[1].disabled = ['1', '3'].includes(detailRes.result.channelType)
          if (detailRes.result.channelType == '1') {
            updateSchema([
              {
                field: 'feeModel',
                componentProps: {
                  disabled: false
                }
              }
            ])
          }
        }
      }
    } catch (error) {
      roleLoading.value = false
    }
  }
  emptyInit.value = true
})

const drawerReset = () => {
  changeOkLoading(false)
  emptyInit.value = false
  drawerInfo.roleIdList = []
  channelTypeStr.value = ''
  roleStr.value = ''
  drawerInfo.checkOptions[0].disabled = false
  drawerInfo.checkOptions[1].disabled = false
  resetFields()
}
// 用户角色搜索过滤
const filterOption = (input: string, option: any) => {
  return option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
// 获取渠道数据
const getChannelList = async (channelRange: string) => {
  const res = await userQueryChannelList({ channelRange })
  channelTreeData.value = transformToTree(res.result)
}
// 勾选值处理
const checkChange = (value: any[]) => {
  let channelRange = '3'
  if (value && value.length == 1) {
    channelRange = value[0]
  }
  getChannelList(channelRange)
  setFieldsValue({
    parentChannelCode: null
  })
}
// 提交数据
const confirmSubmit = async () => {
  if (drawerInfo.type === operateActionTypeMap.VIEW) {
    // emit('resetPwd', drawerInfo.record)
    try {
      changeOkLoading(true)
      await resetPwd({
        userId: drawerInfo.record.userId
      })
      message.success('密码重置成功')
      changeOkLoading(false)
    } catch (error) {
      changeOkLoading(false)
    }
    return
  }
  try {
    await validate()
    let formValue = getFieldsValue()
    formValue.channelCode = formValue.channelFlag == '1' ? formValue.channelCode : null
    formValue.channelName = formValue.channelFlag == '1' ? formValue.channelName : null
    formValue.channelHead = formValue.channelFlag == '1' ? formValue.channelHead : null
    let channelType = null
    if (formValue.channelFlag == '1' && formValue.channelType) {
      if (formValue.channelType.length === 1) {
        channelType = formValue.channelType[0]
      } else if (formValue.channelType.length === 2) {
        channelType = '3'
      }
    }
    formValue.channelType = channelType
    if (formValue.channelFlag == '1' && (channelType == '2' || channelType == '3') && !formValue.feeModel) {
      message.warning('请选择BPai售卖方式')
      changeOkLoading(false)
      return
    }
    changeOkLoading(true)
    if (drawerInfo.type === operateActionTypeMap.ADD) {
      await userAdd({
        ...formValue
      })
    } else if (drawerInfo.type === operateActionTypeMap.EDIT) {
      await userUpdate({
        ...formValue,
        userId: drawerInfo.userId
      })
    }
    message.success(drawerInfo.type === operateActionTypeMap.ADD ? '用户新增成功' : '用户编辑成功')
    closeDrawer()
    drawerReset()
    emit('operateSuccess')
  } catch (error) {
    changeOkLoading(false)
    scrollToFirstError(eleRef.value)
  }
}
</script>

<style lang="less" scoped>
.user-drawer {
  padding: 8px;
  .drawer-flex {
    display: flex;
    align-items: center;
    .switch-info {
      margin-left: 24px;
      display: flex;
      align-items: center;
      .info-txt {
        font-size: 12px;
        color: #c0c0c0;
        margin-left: 4px;
      }
    }
  }
  :deep(.drawer-check) {
    .ant-checkbox-group-item {
      margin-right: 24px;
    }
  }

  .box-auth {
    border: 1px solid #e0e1e6;
    border-radius: 4px;
    position: relative;
    .auth-title {
      height: 44px;
      line-height: 44px;
      padding-left: 4px;
      color: @text-color;
      font-size: 12px;
      font-weight: 600;
      background: #fafafa;
      border-bottom: 1px solid #e0e1e6;
    }
    .auth-list {
      padding: 16px;
      height: 350px;
      overflow: auto;
      position: relative;
      .list-item {
        margin-bottom: 16px;
        color: #606266;
      }
      :deep(.ant-checkbox-group) {
        display: flex;
        flex-direction: column;
        .ant-checkbox-group-item {
          margin-bottom: 16px;
          color: #606266;
        }
      }
    }
  }
  :deep(.ant-form-item-label) {
    font-weight: 600;
  }
}
</style>
